#!/bin/bash

echo "==================================="
echo "  病房管理功能更新脚本"
echo "==================================="
echo ""

# 检查是否在项目根目录
if [ ! -f "docker-compose.yml" ]; then
    echo "[错误] 请在项目根目录运行此脚本！"
    exit 1
fi

# 创建备份目录
BACKUP_DIR="backup_$(date +%Y%m%d_%H%M%S)"
mkdir -p "$BACKUP_DIR"

echo "[1/6] 创建备份..."
# 备份 MongoDB 数据
echo "正在备份数据库..."
docker exec iot_mongodb mongodump --out /tmp/backup
docker cp iot_mongodb:/tmp/backup "$BACKUP_DIR/mongodb_backup"
echo "数据库备份完成: $BACKUP_DIR/mongodb_backup"
echo ""

echo "[2/6] 检查 Docker 服务..."
docker-compose ps
if [ $? -ne 0 ]; then
    echo "[错误] Docker 服务未运行！"
    exit 1
fi
echo ""

echo "[3/6] 停止服务..."
docker-compose down
echo ""

echo "[4/6] 重新构建镜像..."
docker-compose build --no-cache backend frontend
echo ""

echo "[5/6] 启动服务..."
docker-compose up -d
echo ""

echo "[6/6] 等待服务启动..."
sleep 20

echo ""
echo "==================================="
echo "  服务状态检查"
echo "==================================="
docker-compose ps
echo ""

echo "==================================="
echo "  API 健康检查"
echo "==================================="
curl -s http://localhost:5000/api/health | jq . || curl -s http://localhost:5000/api/health
echo ""
echo ""

echo "==================================="
echo "  验证病房管理 API"
echo "==================================="
curl -s http://localhost:5000/api/wards | jq . || curl -s http://localhost:5000/api/wards
echo ""
echo ""

echo "==================================="
echo "  更新完成！"
echo "==================================="
echo "前端地址: http://localhost:3000"
echo "后端地址: http://localhost:5000"
echo "EMQX 控制台: http://localhost:18083"
echo ""
echo "备份位置: $BACKUP_DIR"
echo ""
echo "请在浏览器中验证以下功能："
echo "1. 访问 http://localhost:3000"
echo "2. 点击左侧菜单'病房管理'"
echo "3. 测试添加病房和床位"
echo "4. 测试设备绑定功能"
echo ""

echo "如需查看日志，请运行："
echo "docker-compose logs -f backend frontend"
echo ""

